import utils from '@/utils';
const _routerList = Symbol('_routerList');

const logError = err => console.error(err);

class WxRouter {
  [_routerList] = [];
  constructor(router) {
    this[_routerList] = router;
  }

  go({ url, name, query } = {}) {
    const routerMapItem = this[_routerList].find(
      item => item.url === url || item.name === name
    );
    if (!routerMapItem) {
      logError('找不到路由');
      return;
    }

    const _url = routerMapItem.url;

    if (routerMapItem.isTab) {
      return utils
        .promisify(uni.switchTab)({ url: _url })
        .catch(() =>
          utils.promisify(uni.navigateTo)({
            url: query ? `${_url}?${utils.stringifyQuery(query)}` : _url
          })
        );
    } else {
      return utils
        .promisify(uni.navigateTo)({
          url: query ? `${_url}?${utils.stringifyQuery(query)}` : _url
        })
        .catch(() => utils.promisify(uni.switchTab)({ url: _url }));
    }
  }

  redirect({ url, name, query } = {}) {
    const routerMapItem = this[_routerList].find(
      item => item.url === url || item.name === name
    );
    if (!routerMapItem) {
      logError('找不到路由');
      return;
    }

    const _url = routerMapItem.url;

    if (routerMapItem.isTab) {
      return utils
        .promisify(uni.switchTab)({ url: _url })
        .catch(() =>
          utils.promisify(uni.redirectTo)({
            url: query ? `${_url}?${utils.stringifyQuery(query)}` : _url
          })
        );
    } else {
      return utils
        .promisify(uni.redirectTo)({
          url: query ? `${_url}?${utils.stringifyQuery(query)}` : _url
        })
        .catch(() => utils.promisify(uni.switchTab)({ url: _url }));
    }
  }

  goBack({ delta = 1 } = {}) {
    return utils.promisify(uni.navigateBack)({ delta });
  }

  reLaunch({ url, name, query } = {}) {
    const routerMapItem = this[_routerList].find(
      item => item.url === url || item.name === name
    );
    if (!routerMapItem) {
      logError('找不到路由');
      return;
    }

    const _url = routerMapItem.url;

    return utils.promisify(uni.reLaunch)({
      url: query ? `${_url}?${utils.stringifyQuery(query)}` : _url
    });
  }

  getRouteInfo({ url, name }) {
    return this[_routerList].find(
      item => item.url === url || item.name === name
    );
  }
}

export default WxRouter;
